import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *Description:读写锁
 * 读锁：共享锁。加了读锁，其他线程只能加读锁
 * 写锁：排它锁。加了写锁，其他线程不能再加任何锁
 *Version:1.0.0
 *@author shihb
 *@date 2020/5/24 9:58
 */
public class ReadWriteLockDemo {

  public static void main(String[] args) {
    Demo demo = new Demo();
    for (int i = 0; i < 5; i++) {
      new Thread(()->{
        demo.write(Thread.currentThread().getName(),Thread.currentThread().getName());
      },"Thread"+(i+1)).start();
    }
    for (int i = 0; i < 5; i++) {
      new Thread(()->{
        demo.read(Thread.currentThread().getName());
      },"Thread"+(i+1)).start();
    }

  }
}

class Demo{

  private Map map= new HashMap<String,String>();
  ReadWriteLock rwl = new ReentrantReadWriteLock()  ;
  public void read(String key){
    rwl.readLock().lock();
    try {
      System.out.println("读取"+key);
      map.get(key);
      System.out.println("读取"+key+"完毕");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      rwl.readLock().unlock();
    }
  }
  public void write(String key,String value){
    rwl.writeLock().lock();
    try {
      System.out.println("写入"+key);
      map.put(key,value);
      System.out.println("写入"+key+"完毕");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      rwl.writeLock().unlock();
    }
  }
}


